package com.juno.cafenoa.event;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.juno.cafenoa.Constants;
import com.juno.cafenoa.R;
import com.juno.cafenoa.TopNavigatorView;
import com.juno.cafenoa.net.AsyncTaskCompleteListener;
import com.juno.cafenoa.net.HttpPostTask;
import com.juno.cafenoa.util.Util;
import com.juno.ui.uitableview.UITableView;
import com.juno.ui.uitableview.UITableView.ClickListener;
import com.juno.ui.uitableview.model.ViewItem;

public class EventActivity extends Activity {

	private UITableView mTableView;
	TopNavigatorView navi = null;
	ProgressBar pb = null;
	Context mContext;
	ArrayList<Event> eventList;
	TextView noList;
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_event);
		mContext = this;
		mTableView = (UITableView) findViewById(R.id.eventTableView);
		navi = (TopNavigatorView) findViewById(R.id.navi_event);
		pb = (ProgressBar) findViewById(R.id.event_Process_PB);
		noList = (TextView) findViewById(R.id.no_event_list);
		noList.setVisibility(View.GONE);
		navi.init("Event");
		
		eventList = new ArrayList<Event>();
		pb.setVisibility(View.VISIBLE);
	}
	
	
	
	@Override
	protected void onResume() {
		super.onResume();
		mTableView.clear();
		eventList.clear();
		
		getListListener.excuteHttpTask();
	}



	protected UITableView getUITableView(){
		return mTableView;
	}
	
	/**
	 * 막코딩되어있음. 나중에 참조바람.
	 * 서버 통신시 이미지 url, 이벤트 타이틀, 이벤트 유효시간 가져옴.
	 */
	protected void getList(){
		CustomClickListener listener = new CustomClickListener();
		mTableView.setClickListener(listener);
		RowView row  = null;
		for(int i=0;i<eventList.size();i++){
			row = new RowView(this , eventList.get(i).name, eventList.get(i).stopTime+"까지");
			mTableView.addViewItem(new ViewItem(row));
		}		
		mTableView.commit();
		pb.setVisibility(View.GONE);
	}
	
	private class CustomClickListener implements ClickListener{

		@Override
		public void onClick(int index) {
			AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
			builder.setTitle(eventList.get(index).name);
			builder.setMessage(eventList.get(index).content);
			builder.setPositiveButton("확인", new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}
			});
			AlertDialog ad = builder.create();
			ad.show();
		}
		
	}
	
	
	
	/**
	 * 이벤트 listview에 추가될 한 row단위 정위.
	 * 
	 * @author JUNHO
	 */
	public class RowView extends RelativeLayout{
		private Context context;
		private TextView eventTitle;
		private TextView eventDate;
		
		public RowView(Context context, String eventTitle, String eventDate) {
			super(context);
			this.context = context;
			init();
			this.eventTitle.setText(eventTitle);
			this.eventDate.setText(eventDate);
		}
		
		/**
		 * inflater로 정의된 layout 받아옴.
		 */
		public void init(){
			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			inflater.inflate(R.layout.event_list_row, this);
			eventTitle = (TextView) findViewById(R.id.eventTitle);
			eventDate = (TextView) findViewById(R.id.eventDate);
		}
	}
	
	AsyncTaskCompleteListener getListListener = new AsyncTaskCompleteListener(){

		@Override
		public void excuteHttpTask() {
			//Url 세팅.
			String url = Util.getUrl("EventInfo");
			
			//name value pair에 id와 password 세팅
			ArrayList<NameValuePair> value = new ArrayList<NameValuePair>();
			value.add(new BasicNameValuePair("REQUEST_EVENT", "1"));
			
			//httpPostTast 실행.
			HttpPostTask http = new HttpPostTask(mContext, value, url, getListListener);
			http.execute();
		}

		@Override
		public void onTaskComplete(String result, boolean taskOk) {
			//http 통신 실행후 서버로부터 오는 내용.
			//작업이 모두 완료되었다면.
			Log.v("result","reuslt :" + result);
			if(taskOk){
				int code = -1;
				try {
					JSONObject object = new JSONObject(result);
					code = object.getInt("RESULT");
					
					if(code==Constants.NETWORK_SUCCESS){
						String surpriceSt = object.getString("EVENT_STATE");
						boolean state = (surpriceSt.equalsIgnoreCase("true") ) ? true:false;
						
						JSONArray jArr = object.getJSONArray("ITEM");
						if(jArr.length()==0){
							noList.setVisibility(View.VISIBLE);
							pb.setVisibility(View.GONE);
							return;
						}
						int i = -1;
						
						if(state){
							JSONObject obj = jArr.getJSONObject(0);

							String title = obj.getString("EVENT_NAME");
							String content = obj.getString("EVENT_CONTENT");
							String startTime = obj.getString("EVENT_START_TIME");
							String stopTime = obj.getString("EVENT_STOP_TIME");
							
							AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
							builder.setTitle(title + "깜짝이벤트");
							builder.setMessage(content+"\n"+startTime+"부터 "+stopTime+"까지");
							builder.setPositiveButton("확인", new OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									
								}
							});
							AlertDialog ad = builder.create();
							ad.show();
							i = 1;
						} else
							i = 0;
						
						int id	=-1;
						String name = null;
						String content = null;
						String startTime = null;
						String stopTime = null;
						
						for(;i<jArr.length();i++){
							JSONObject obj = jArr.getJSONObject(i);
							id = obj.getInt("EVENT_ID");
							name = obj.getString("EVENT_NAME");
							content = obj.getString("EVENT_CONTENT");
							startTime = obj.getString("EVENT_START_TIME");
							stopTime = obj.getString("EVENT_STOP_TIME");
						
							eventList.add(new Event(id, name, content, startTime, stopTime));
						}
						getList();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		
	};
	
	class Event{
		int id;
		String name;
		String content;
		String startTime;
		String stopTime;
		
		public Event(int id, String name, String content, String startTime, String stopTime){
			this.id = id;
			this.name = name;
			this.content = content;
			this.startTime = startTime;
			this.stopTime = stopTime;			
		}
		
	}
	
}
